/**
 * 易驰护运 - Calculation
 * http://menger.me
 * @桓桓
 */

'use strict';

import React from 'react'
import { 
    View, 
    Text, 
    Keyboard,
    TextInput, 
    StyleSheet, 
    ScrollView, 
    ImageBackground, 
    TouchableOpacity, 
} from 'react-native'
import {inject, observer} from 'mobx-react'

@inject('loginStore')
@observer
export default class Calculation extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            messageView: false,
            goodsSource: [],
            startLongitude: '',
            startLatitude: '',
            endLongitude: '',
            endLatitude: '',
            // submit
            goods_name: '',
            startMarkers: '',
            endMarkers: '',
            weight: '',
            goods_price: '',
            // show
            distance: '',
        }
    }

    componentDidMount() {
        this.requestUnit();
        this.requestGoodsData();
    }

    requestUnit = async () => {
        let url = ServicesApi.GOODS_UNIT;
        let data = {};
        const result = await Services.post(url, data);
        if (result.code === StatusCode.SUCCESS_CODE) {
            this.setState({
                goods_price: result.data,
            });
        }
    }

    requestGoodsData = async () => {
        let url = ServicesApi.GOODS_PRODUCT_LIST;
        let data = {};
        const result = await Services.post(url, data);
        if (result.code === StatusCode.SUCCESS_CODE) {
            this.setState({
                goodsSource: result.data
            });
        }
    }

    getAddress = (type, markers) => {
        let arr = markers.split("|");
        type == 'start'
        ?   this.setState({
                startMarkers: arr[0],
                startLongitude: arr[1],
                startLatitude: arr[2],
            })
        :   this.setState({
                endMarkers: arr[0],
                endLongitude: arr[1],
                endLatitude: arr[2],
            })
    }

    //点击顶部商品按钮（点完算距离）
    onPressGoodsBtn = (item) => {
        this.setState({
            goods_name: item.name,
            goods_price: item.suggest_unit_price_text,
        })
    }

    onSubmit = async () => {
        let {startMarkers, endMarkers, weight, startLongitude, startLatitude, endLongitude, endLatitude,} = this.state;
        if (startMarkers == '') {
            ToastManager.message('请选择出发地');
            return
        }
        if (endMarkers == '') {
            ToastManager.message('请选择目的地');
            return
        }
        if (weight == '') {
            ToastManager.message('请填写吨数');
            return
        }
        let url = ServicesApi.MEASURE_MATH;
        let data = {
            origins: startLongitude + ',' + startLatitude,
            destination: endLongitude + ',' + endLatitude,
        }
        const result = await Services.post(url, data);
        if (result.code === StatusCode.SUCCESS_CODE) {
            this.setState({
                messageView: true,
                distance: result.data,
            })
            ToastManager.success(result.msg);
        } else {
            this.setState({messageView: false})
            ToastManager.fail(result.msg);
        }
    }

    goodsView = (data) => {
        let {goods_name} = this.state;
        let contain = data.map((item, index) => {
            if (item.sort > 0) {
                return (
                    <Button
                        key={index}
                        style={styles.goodsBtn}
                        title={item.name}
                        titleStyle={styles.goodsBtnTitle}
                        onPress={() => this.onPressGoodsBtn(item)}
                    />
                )
            }
        })
        let contain1 = data.map((item, index) => {
            if ( item.name.includes(goods_name) && goods_name !== '' ) {
                return (
                    <Button
                        key={index}
                        style={styles.goodsBtn}
                        title={item.name}
                        titleStyle={styles.goodsBtnTitle}
                        onPress={() => this.onPressGoodsBtn(item)}
                    />
                )
            }
        })

        return <View style={styles.goodsBox}>{contain}{contain1}</View>
    }
    
    render() {
        let {
            messageView, goodsSource,
            distance, startLongitude, startLatitude, endLongitude, endLatitude,
            goods_name, startMarkers, endMarkers, weight, goods_price,
        } = this.state;
        return (
            <PageContainer style={styles.container}>
                <NavigationBar
                    title={'运费测算'}
                    style={[styles.navigationBarStyle]}
                />
                <View style={styles.from}>
                    <View style={styles.line}>
                        <Text style={styles.lineLeft}>货物名称<Text style={{color: '#E71425'}}>*</Text></Text>
                        <TextInput
                            defaultValue={goods_name}
                            placeholder={'请输入货物名称'}
                            style={styles.lineRightInput}
                            placeholderTextColor={'#999'}
                            onChangeText={(text) => this.setState({goods_name: text})}
                        />
                    </View>
                    {this.goodsView(goodsSource)}
                    <TouchableOpacity 
                        style={styles.line}
                        onPress={() => RouterHelper.navigate('', 'MapComponentWeb', {
                            markersType: 'start',
                            default_address: startMarkers,
                            getAddress: (type, markers) => this.getAddress(type, markers)
                        })}
                    >
                        <Text style={styles.lineLeft} numberOfLines={1}>出发地具体地址<Text style={{color: '#E50114'}}>*</Text>:</Text>
                        <Text style={[styles.lineRightInput, !startLongitude && {color: '#999'}]}>
                            {startMarkers == '' ? '请选择出发地具体地址' : startMarkers}
                        </Text>
                    </TouchableOpacity>
                    <TouchableOpacity 
                        style={styles.line}
                        onPress={() => RouterHelper.navigate('', 'MapComponentWeb', {
                            markersType: 'end',
                            default_address: endMarkers,
                            getAddress: (type, markers) => this.getAddress(type, markers)
                        })}
                    >
                        <Text style={styles.lineLeft} numberOfLines={1}>目的地具体地址<Text style={{color: '#E50114'}}>*</Text>:</Text>
                        <Text style={[styles.lineRightInput, !endLongitude && {color: '#999'}]}>
                            {endMarkers == '' ? '请选择目的地具体地址' : endMarkers}
                        </Text>
                    </TouchableOpacity>  
                    <View style={styles.line}>
                        <Text style={styles.lineLeft} numberOfLines={1}>货物吨数<Text style={{color: '#E50114'}}>*</Text>:</Text>
                        <TextInput
                            defaultValue={weight}
                            style={styles.lineRightInput}
                            placeholder={'请输入货物吨数'}
                            placeholderTextColor={'#999'}
                            onChangeText={(text) => this.setState({weight: text})}
                        />
                    </View>    
                    <View style={styles.line}>
                        <Text style={styles.lineLeft} numberOfLines={1}>货物价格(系数)<Text style={{color: '#E50114'}}>*</Text>:</Text>
                        <TextInput
                            editable={false}
                            defaultValue={goods_price}
                            style={styles.lineRightInput}
                            placeholder={'货物价格(系数)'}
                            placeholderTextColor={'#999'}
                            onChangeText={(text) => this.setState({goods_price: text})}
                        />
                    </View>  
                </View>
                {
                    messageView == true &&
                    <View style={styles.message}>
                        <View style={styles.messageLine}>
                            <Text style={styles.messageTitle} numberOfLines={1}>计算结果</Text>
                        </View>
                        <View style={styles.messageLine}>
                            <Text style={styles.messageLineLeft} numberOfLines={1}>参考距离： </Text>
                            <Text style={styles.messageLineRight} numberOfLines={1}>{distance || 0}km</Text>
                        </View>  
                        <View style={styles.messageLine}>
                            <Text style={styles.messageLineLeft} numberOfLines={1}>建议运输单价: </Text>
                            <Text style={styles.messageLineRight} numberOfLines={1}>{(goods_price * distance).toFixed(2) || 0}元/吨</Text>
                        </View>
                        <View style={styles.messageLine}>
                            <Text style={styles.messageLineLeft} numberOfLines={1}>运费预计: </Text>
                            <Text style={styles.messageLineRight} numberOfLines={1}>￥{(goods_price * distance * weight).toFixed(2) || 0}</Text>
                        </View>
                    </View>    
                }
                <View style={styles.btnBox}>
                    <Button
                        style={styles.btn}
                        title={'计算运费'}
                        titleStyle={styles.btnTitle}
                        resizeMode={'cover'}
                        backgroundImage={Images.img_btn_bg1}
                        onPress={() => this.onSubmit()}
                    />
                </View>
            </PageContainer>
        );
    }
}

const DominantColor = '#00BFCC';
const styles = StyleSheet.create({
    container: {
        backgroundColor: '#f2f2f2',
    },

    from: {
        backgroundColor: '#fff',
    },
    line: {
        flexDirection: 'row',
        justifyContent: 'space-between',
        alignItems: 'center',
        height: 50,
        marginHorizontal: 15,
        borderBottomWidth: Predefine.minPixel,
        borderBottomColor: '#e1e1e1',
    },
    lineLeft: {
        fontSize: 14,
        color: '#333',
    },
    lineRight: {
        flexDirection: 'row',
        alignItems: 'center',
    },
    lineRightText: {
        fontSize: 14,
        color: '#999',
    },
    lineRightImg: {
        width: 6,
        height: 12,
        marginLeft: 5,
    },
    lineRightInput: {
        flex: 1,
        textAlign: 'right',
        fontSize: 14,
        color: '#666',
    },
    lineRightBox: {
        flex: 1,
        flexDirection: 'row',
        justifyContent: 'space-between',
        alignItems: 'center',
    },
    lineRightArrow: {
        width: 6,
        height: 10,
        marginLeft: 5,
    },

    goodsBox: {
        flexDirection: 'row',
        flexWrap: 'wrap',
        marginTop: 10,
    },
    goodsBtn: {
        backgroundColor: DominantColor,
        paddingHorizontal: 6,
        paddingVertical: 0,
        height: 26,
        marginHorizontal: 5,
        marginBottom: 10,
    },

    message: {
        marginTop: 10,
        backgroundColor: '#fff',
    },
    messageTitle: {
        fontSize: 15,
        color: DominantColor,
    },
    messageLine: {
        flexDirection: 'row',
        justifyContent: 'space-between',
        alignItems: 'center',
        height: 50,
        paddingHorizontal: 15,
    },
    messageLineLeft: {
        fontSize: 14,
    },
    messageLineRight: {
        fontSize: 14,
    },

    btnBox: {
        padding: 15,
        backgroundColor: '#fff',
    },
    btn: {
        backgroundColor: DominantColor,
    },
});